package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.common.RpcServer;
import com.lagou.rpc.consumer.client.RpcClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 * @author: yx
 * @date: 2022/1/11 16:31
 */
public class RpcClientProxy {

    private static AtomicInteger NEXT_SERVER_COUNTER = new AtomicInteger(0);

    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameters(args);
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        //2.创建RpcClient对象
                        RpcServer rpcServer = selectServer();
                        System.out.println(String.format("给ip: %s,port: %s发送消息", rpcServer.getIp(), rpcServer.getPort()));
                        RpcClient rpcClient = new RpcClient(rpcServer.getIp(), rpcServer.getPort());
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            System.out.println("出异常了: " + e.getMessage());
                            throw e;
                        } finally {
                            rpcClient.close();
                        }
                    }
                });
    }

    public static int getServerIndex(int modulo) {
        for (; ; ) {
            int current = NEXT_SERVER_COUNTER.get();
            int next = (current + 1) % modulo;
            boolean result = NEXT_SERVER_COUNTER.compareAndSet(current, next);
            if (result) {
                return next;
            }
        }
    }

    public static RpcServer selectServer() {
        List<RpcServer> rpcServerList = new ArrayList<>();
        RpcServer rpcServer = new RpcServer("127.0.0.1", 8899);
        RpcServer rpcServer2 = new RpcServer("127.0.0.1", 8898);
        rpcServerList.add(rpcServer);
        rpcServerList.add(rpcServer2);
        return rpcServerList.get(getServerIndex(rpcServerList.size()));
    }
}
